<?php
//define your token
define("TOKEN", "wanya");
require_once '../init.php';

$wechatObj = new wechatCallbackapi();
if(isset($_GET["echostr"])){ #验证过token，成为开发者之后，可以直接$wechatObj->responseMsg();
	$wechatObj->valid();
}
else{
	$wechatObj->responseMsg();
}
class wechatCallbackapi{
	public function valid(){
		$echoStr = $_GET["echostr"];
        //valid signature , option
        if($this->checkSignature()){
        echo $echoStr;
        exit;
        }
    }

    public function responseMsg(){
	//get post data, May be due to the different environments
	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    //extract post data
	if (!empty($postStr)){
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); #这里有从用户通过公众平台接收过来的数据，具体是什么类型的数据，开发者文档上写的很清楚，可以去上面查。
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
		$keyword = trim($postObj->Content);
		$msgType = $postObj->MsgType;
        $time = time();
		switch( $msgType ){
			case "event": #这个是事件的操作，当关注的时候自动回复
				$Wx_Push_Model = new Wx_Push_Model();
				$wxPush = $Wx_Push_Model->getWxPushForUpdate(1);
				$textTpl = "<xml>
				<ToUserName><![CDATA[%s]]></ToUserName>
				<FromUserName><![CDATA[%s]]></FromUserName>
				<CreateTime>%s</CreateTime>
				<MsgType><![CDATA[%s]]></MsgType>
				<ArticleCount>1</ArticleCount>
				<Articles>
				<item>
				<Title><![CDATA[{$wxPush["title"]}]]></Title>
				<Description><![CDATA[{$wxPush["description"]}]]></Description>
				<PicUrl><![CDATA[{$wxPush["picurl"]}]]></PicUrl>
				<Url><![CDATA[{$wxPush["url"]}]]></Url>
				</item>
				<item>
				</Articles>
				</xml>";
				$event = $postObj->Event;
				$msgType = "news";
				if( $event =='subscribe'){
					$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType);

				}
				break;
			case "text":
				$resultStr = $this->transmitService($postObj);
				break;
		}
		echo $resultStr;
		}
		else {
			echo "";
			exit;
		}
	}

	//接收文本消息,转发给多客服
	private function transmitService($object)
	{
		$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
		$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
		return $result;
	}

	private function checkSignature(){
		 $signature = $_GET["signature"];
		 $timestamp = $_GET["timestamp"];
		 $nonce = $_GET["nonce"];   
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		if( $tmpStr == $signature ){
		return true;
		}else{
		return false;
		}
	}
}
?>